package com.androidlongs.asynchttpcilenlibrary;


import android.text.*;
import android.util.*;

import com.loopj.android.http.*;

import java.util.*;
import java.util.Map.*;

/**
 * Created by androidlongs on 17/7/17.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

public class HttpClientRequestUtils {

    private final String TAG = "library_httpclient";
    private final AsyncHttpClient mAsyncHttpClient;

    private static class SingleRuequestUtils {
        private static HttpClientRequestUtils sHttpClientRequestUtils = new HttpClientRequestUtils();
    }

    public static HttpClientRequestUtils getIntance () {
        return SingleRuequestUtils.sHttpClientRequestUtils;
    }

    private HttpClientRequestUtils () {
        // 创建异步请求端对象
        mAsyncHttpClient = new AsyncHttpClient();
        //设置超时时间
        mAsyncHttpClient.setTimeout(30000);
    }


    /**
     * get请求方法
     */
    public RequestHandle sendGetFunction (
            String url,
            final Class<?> cl,
            final CommonAsyHttpClientResponsLiserner liserner) {
        return sendGetFunction(url,null,null, cl,liserner);
    }
    public RequestHandle sendGetFunction (
            String url,
            Map<String, String> keyMap,
            final Class<?> cl,
            final CommonAsyHttpClientResponsLiserner liserner) {
        return sendGetFunction(url, null,keyMap,cl, liserner);
    }

    /**
     * post请求方法
     *
     * @param url
     *         请求链接
     * @param keyMap
     *         请求参数
     * @param cl
     *         请求数据结果 数据对应模型
     * @param liserner
     *         回调
     */
    public RequestHandle sendGetFunction (
            String url,
            Map<String, String> headerMap,
            Map<String, String> keyMap,
            final Class<?> cl,
            final CommonAsyHttpClientResponsLiserner liserner) {

        /**
         * 封装请求Header
         */
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Entry<String, String> entry : headerMap.entrySet()) {
                mAsyncHttpClient.addHeader(entry.getKey(),entry.getValue());
            }
        }
        /**
         * 封装请求参数
         */
        if (keyMap != null && !keyMap.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder(url);
            stringBuilder.append("?time=");
            stringBuilder.append(System.currentTimeMillis());
            Set<Entry<String, String>> entries = keyMap.entrySet();
            for (Entry<String, String> entry : entries) {
                stringBuilder.append("&");
                stringBuilder.append(entry.getKey());
                stringBuilder.append("=");
                stringBuilder.append(entry.getValue());
            }
            url = stringBuilder.toString();
        }
        //创建请求回调
        TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure (int i, org.apache.http.Header[] headers, String s, Throwable throwable) {
                Log.e(TAG, "请求失败");
                if (liserner != null) {
                    liserner.onFaile("请求失败 " + s + " " + throwable.getMessage(), -1);
                }
            }

            @Override
            public void onSuccess (int i, org.apache.http.Header[] headers, String s) {
                Log.d(TAG, "请求成功 " + s);
                if (TextUtils.isEmpty(s)) {
                    if (liserner != null) {
                        liserner.onFaile("请求失败 请求结果为 null", -2);
                    }
                } else {
                    Object o = FastJsonUtil.toBean(s, cl);
                    if (liserner != null) {
                        liserner.onSuccess(o, s);
                    }

                }
            }
        };
        // 发送get请求对象
        return mAsyncHttpClient.get(url, textHttpResponseHandler);
    }



    /**
     * 发送Post请求
     */
    public RequestHandle sendPostFunction (
            String url,
            final Class<?> cl,
            final CommonAsyHttpClientResponsLiserner liserner) {
        return sendPostFunction(url, null, liserner);
    }

    public RequestHandle sendPostFunction (
            String url,
            Map<String, String> keyMap,
            final Class<?> cl,
            final CommonAsyHttpClientResponsLiserner liserner) {

        /**
         * 封装请求参数
         */
        RequestParams requestParams = new RequestParams();
        if (keyMap != null && !keyMap.isEmpty()) {
            Set<Entry<String, String>> entries = keyMap.entrySet();
            for (Entry<String, String> entry : entries) {
                requestParams.put(entry.getKey(), entry.getValue());
            }
        }
        //创建请求回调
        TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure (int i, org.apache.http.Header[] headers, String s, Throwable throwable) {
                Log.e(TAG, "请求失败");
                if (liserner != null) {
                    liserner.onFaile("请求失败 " + s + " " + throwable.getMessage(), -1);
                }
            }

            @Override
            public void onSuccess (int i, org.apache.http.Header[] headers, String s) {
                Log.d(TAG, "请求成功 " + s);
                if (TextUtils.isEmpty(s)) {
                    if (liserner != null) {
                        liserner.onFaile("请求失败 请求结果为 null", -2);
                    }
                } else {
                    Object o = FastJsonUtil.toBean(s, cl);
                    if (liserner != null) {
                        liserner.onSuccess(o, s);
                    }

                }
            }
        };
        return mAsyncHttpClient.post(url, requestParams, textHttpResponseHandler);
    }
}
